﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace Utils
{
    /// <summary>
    /// 比较器
    /// </summary>
    public abstract class ComparerHelper
    {
        public static IEqualityComparer<T> CreateEqualityComparer<T>(Func<T, object> a)
        {
            return new DefaultEqualityComparer<T, object>(a);
        }

        public static IComparer<T> CreateComparer<T>(Func<T, object> a)
        {
            return new DefaultComparer<T, object>(a);
        }
    }
    public class DefaultComparer<T, KEY> : IComparer<T>
    {
        private readonly Func<T, KEY> func;
        public DefaultComparer(Func<T, KEY> func)
        {
            this.func = func;
        }

        public int Compare(T x, T y)
        {
            return Comparer.Default.Compare(func(x), func(y));
        }
    }
    /// <summary>
    /// 比较器
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class DefaultEqualityComparer<T, KEY> : IEqualityComparer<T>
    {
        private readonly Func<T, KEY> func;
        public DefaultEqualityComparer(Func<T, KEY> func)
        {
            this.func = func;
        }

        public bool Equals(T x, T y)
        {
            return object.Equals(func(x), func(y));
        }

        public int GetHashCode(T obj)
        {
            var o = func(obj);
            if (o == null)
            {
                return 0;
            }
            return o.GetHashCode();
        }
    }
}
